package com.yy.wmmaccmsapp

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.util.Log
import android.view.KeyEvent
import android.widget.Toast
import androidx.core.content.FileProvider
import androidx.fragment.app.FragmentTransaction
import androidx.lifecycle.Observer
import com.google.gson.Gson
import com.gyf.immersionbar.ImmersionBar
import com.hjq.permissions.OnPermissionCallback
import com.hjq.permissions.Permission
import com.hjq.permissions.XXPermissions
import com.mylhyl.circledialog.CircleDialog
import com.mylhyl.circledialog.view.listener.OnButtonClickListener
import com.mylhyl.circledialog.view.listener.OnInputClickListener
import com.yy.wmmaccmsapp.base.BaseActivity
import com.yy.wmmaccmsapp.bean.KamiBean
import com.yy.wmmaccmsapp.databinding.ActivityMainBinding
import com.yy.wmmaccmsapp.http.Errocallback
import com.yy.wmmaccmsapp.main.MainViewModel
import com.yy.wmmaccmsapp.utils.CacheUtil
import com.yy.wmmaccmsapp.utils.TimerWithCallback
import com.yy.wmmaccmsapp.web.AgentWebFragment
import com.yy.wmmaccmsapp.web.FragmentKeyDown
import me.hgj.jetpackmvvm.ext.parseState
import me.hgj.jetpackmvvm.ext.util.toJson
import java.io.File


class MainActivity : BaseActivity<MainViewModel, ActivityMainBinding>() {


    var mAgentWebFragment: AgentWebFragment? = null


    override fun onKeyDown(keyCode: Int, event: KeyEvent?): Boolean {
        val mAgentWebFragment: AgentWebFragment = mAgentWebFragment!!
        if (mAgentWebFragment != null) {
            val mFragmentKeyDown: FragmentKeyDown = mAgentWebFragment
            return if (mFragmentKeyDown.onFragmentKeyDown(keyCode, event)) {
                true
            } else {
                super.onKeyDown(keyCode, event)
            }
        }
        return super.onKeyDown(keyCode, event)
    }

    fun getActiveState() {
        mViewModel.kamiInfo.observe(this, Observer {
            parseState(it, {

                var jsonStr = it?.toJson().toString()
                Log.e("zyj..", jsonStr)

                if (jsonStr.contains("errorLog")) {
                    var error = Gson().fromJson(jsonStr, Errocallback::class.java)
                    error?.let {
                        Toast.makeText(applicationContext, error.errorLog, Toast.LENGTH_SHORT)
                            .show()
                    }
                } else if (jsonStr.contains("cardPasswd")) {
                    var kamiBean = Gson().fromJson(jsonStr, KamiBean::class.java)
                    CacheUtil.setKamiInfo(jsonStr)
                    Toast.makeText(
                        applicationContext,
                        "恭喜激活${kamiBean.enUse}天Vip权益",
                        Toast.LENGTH_SHORT
                    ).show()
                    hideKamiDialog()
                }


            }, {
                Log.e("zyj..", it?.toJson().toString())
            })
        })


    }

    override fun onResume() {
        super.onResume()
        startCheckActive()
        checkAppUpdate()
    }

    fun checkAppUpdate(){
        applicationContext.externalCacheDir?.let { mViewModel?.checkAppUpdate(it?.absolutePath,BuildConfig.VERSION_CODE) }
    }

    override fun onStop() {
        super.onStop()
        stopCheckActive()
    }

    val timer = TimerWithCallback(1000, 10 * 1000) // 延迟1秒，周期2秒
    fun startCheckActive() {

        getActiveState()

        timer.startTimer {
            // println("Timer ticked!")

            checkActiveState()

        }
    }

    fun checkActiveState() {
        //CacheUtil.removeKey("kamiinfo")
        var fristTime = CacheUtil.getFristTime()
        if (fristTime.toInt() == -1) {
            CacheUtil.setFristTime(System.currentTimeMillis() / 1000)
            fristTime = CacheUtil.getFristTime()
        }


        var kamiBean = CacheUtil.getKamiInfo()
         var isShowTime =  60 * 60
        //var isShowTime = 30
        if (kamiBean != null) {

            isShowTime = kamiBean.enUse * 24 * 60 * 60
        }

        var nowTime = System.currentTimeMillis() / 1000

        var chaTime = nowTime - fristTime
//        Log.e("zyj..",
//            "nowTime.......$nowTime....fristTime.......$fristTime....isShowTime.......$isShowTime.......chaTime....$chaTime"
//        )
        if (chaTime >= isShowTime) {
            showDialogKami()
        }

    }

    fun showDialogKami() {
        runOnUiThread {
            showKamiDialog()
        }
    }


    var dialogKami: CircleDialog.Builder? = CircleDialog.Builder()
        //添加标题，参考普通对话框
        .setInputText("")//输入框默认文本
        //.setInputText("", "请输入卡密")//输入框默认文本，提示
        .setInputHint("请输入卡密")//提示
        .setInputHeight(40)//输入框高度
        // .setInputCounter(16)//输入框的最大字符数，默认格式在输入右下角例如：20
        //.setInputCounterColor(color)//最大字符数文字的颜色值
        .setInputShowKeyboard(true)//自动弹出键盘
        .setCanceledOnTouchOutside(false)
        //输入框的最大字符数
        //OnInputCounterChangeListener灵活配置格式 例如：maxLen - currentLen + "/" + maxLen 最终效果是：10/20
        //.setInputCounter(maxLen, OnInputCounterChangeListener)
        // .configInput(ConfigInput)//配置输入框更多的属性
        // .setNegative("取消", On)
        // .configNegative(ConfigButton)//配置取消按钮更多的属性
        .setPositiveInput("确定", OnInputClickListener { text, editText ->
            mViewModel.getKamiInfo(text)

            return@OnInputClickListener false
        })

    var isKamiShow = false
    fun showKamiDialog() {
        if (!isKamiShow) {
            isKamiShow = true
            dialogKami?.show(supportFragmentManager)
        }

    }

    fun hideKamiDialog() {

        isKamiShow = false
        dialogKami?.dismiss()


    }


    fun stopCheckActive() {
        isKamiShow = false
        timer.stopTimer()
    }

    override fun disaleScreenCopy(): Boolean {
        return false
    }

    override fun initView(savedInstanceState: Bundle?) {
        // mDatabind.m = mViewModel
        //getActiveState()
        CacheUtil.initMMKV(applicationContext)

        var mImmersionBar = ImmersionBar.with(this);
        //根据自己的需要添加上需要的方法如
        mImmersionBar.transparentStatusBar()
        //最后通过.init()方法载入
        mImmersionBar.init()


        val ft: FragmentTransaction = supportFragmentManager.beginTransaction()

        var mBundle = Bundle()
        mBundle.putString(AgentWebFragment.URL_KEY, "https://ceshi.letui.link")
        mAgentWebFragment = AgentWebFragment.getInstance(mBundle)
        ft.add(R.id.nav_host_fragment_content_main, mAgentWebFragment!!).commit()

        //dialogKami?.show(supportFragmentManager)

        mViewModel?.updateInfoUrl.observe(this) {
            if("no update".equals(it)){

            }else{
                showAppUpdateDialog(it)
            }

        }

        mViewModel?.updateDownloadProgress.observe(this){
            appDownloadDialog?.setProgress(100,it)
            appDownloadDialog?.refresh()
        }

        mViewModel?.appStartInstall.observe(this){
            appDownloadDialog?.dismiss()
            startInstall(applicationContext,File(it))
        }

    }

    /**
     * 安装apk 自动
     */
    fun startInstall(mContext: Context,mApkFile:File) {
        mContext.startActivity(preInatall(mContext, mApkFile))
    }

    private fun preInatall(context: Context, file: File): Intent? {
        if (!file.exists()) {
            return null
        }
        //安装
        val install = Intent(Intent.ACTION_VIEW)
        Log.i("getApplication-", context.getApplicationContext().getPackageName())
        //判断是否是android 7.0及以上
        if (Build.VERSION.SDK_INT >= 24) {
            //7.0获取存储文件的uri
            val uri: Uri = FileProvider.getUriForFile(
                context,
                context.getApplicationContext().getPackageName().toString() + ".provider",
                file
            )
            install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
            //赋予临时权限
            install.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            //设置dataAndType
            install.setDataAndType(uri, "application/vnd.android.package-archive")
        } else {
            if (file.exists()) {
                install.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
                install.setDataAndType(
                    Uri.fromFile(file),
                    "application/vnd.android.package-archive"
                )
            }
        }
        return install
    }


    var appUpdateDialog:CircleDialog.Builder? = null


    fun showAppUpdateDialog(url:String){
        appUpdateDialog = CircleDialog.Builder()
            .setTitle("APP更新")
            //标题字体颜值 0x909090 or Color.parseColor("#909090")
            //.setTitleColor(@ColorInt color)
            //.setTitleIcon(@DrawableRes icon)//标题图标
            // .configTitle(ConfigTitle)//配置标题更多的属性
            //如果 ConfigTitle 不能满足你，此监听器可以帮助你
            //.setOnCreateTitleListener(OnCreateTitleListener)
            //.setSubTitle(subTitle)//副标题
            //副标题字体色值 0x909090 or Color.parseColor("#909090")
            //.setSubTitleColor(@ColorInt color)
            //.configSubTitle(ConfigSubTitle)//配置标题更多的属性
            .setText("APP有新的版本更新")//内容
            //.setTextColor(@ColorInt color)//内容字体色值
            //.configText(ConfigText)//配置内容更多的属性
            //如果 ConfigText 不能满足你，此监听器可以帮助你
            // .setOnCreateTextListener(OnCreateTextListener)
            .setPositive("确定", OnButtonClickListener {

                checkInstallAppPermission(url)

                return@OnButtonClickListener true
            })
            //.configPositive(ConfigButton)//配置确定按钮更多的属性
            .setNegative("取消", OnButtonClickListener {

                return@OnButtonClickListener true
            })
        //.configNegative(ConfigButton)//配置取消按钮更多的属性
        // .setNeutral("中间", OnClickListener)
        //.configNeutral(ConfigButton)//配置中间按钮更多的属性
        //如果 configPositive configNegative configNeutral 不能满足你，此监听器可以帮助你
        // .setOnCreateButtonListener(OnCreateButtonListener)

        appUpdateDialog?.show(supportFragmentManager)
    }

    fun checkInstallAppPermission(url: String){
        appUpdateDialog?.dismiss()
        XXPermissions.with(this)
            //.permission(Permission.WRITE_EXTERNAL_STORAGE)
            .permission(Permission.REQUEST_INSTALL_PACKAGES)
            .request(object : OnPermissionCallback {
                override fun onGranted(permissions: MutableList<String>, allGranted: Boolean) {
                    applicationContext.externalCacheDir?.let { mViewModel?.doAppUpdate(it?.absolutePath,url) }
                    showAppDownloadDialog()
                }

                override fun onDenied(permissions: MutableList<String>, doNotAskAgain: Boolean) {

                }

            })
    }

    var appDownloadDialog:CircleDialog.Builder? = null
    fun showAppDownloadDialog(){
         appDownloadDialog =  CircleDialog.Builder()
            //添加标题，参考普通对话框
            //.setProgressStyle(style)//STYLE_HORIZONTAL 或 STYLE_SPINNER
            .setProgressText("已经下载%s")// style = 水平样式时，text支持String.format() 例如：已经下载%s
           // .setProgressText(text,timeoutText) // 5.3.6添加 timeoutText超时显示文本，依赖于 setPositiveTime()
            .setProgress(100, 1)//水平样式的最大刻度和当前刻度
           // .setProgressDrawable(@DrawableRes int progressDrawableId)//自定义进度样式资源文件
            .setProgressHeight(40)//进度条的高度
           // .configProgress(ConfigProgress)//配置进度框更多的属性
           // .setPositive("确定", OnClickListener)
           // .setPositiveTime(countDownTime, countDownInterval, countDownText,countDownTimerObserver)
           // .configPositive(ConfigButton)//配置确定按钮更多的属性
           // .setNegative("取消", OnClickListener)
           // .configNegative(ConfigButton)//配置取消按钮更多的属性
           // .setNeutral("中间", OnClickListener)
           // .configNeutral(ConfigButton)//配置中间按钮更多的属性
          appDownloadDialog?.show(supportFragmentManager)

    }

}